import { FamilyInfo, familyUpdate } from "@/services/family/api";
import { ModalForm, ProForm, ProFormSelect } from "@ant-design/pro-components";
import { Form, message } from "antd";
import to from "await-to-js";
import { type FC, useEffect } from 'react';

type ReportSettingModalProps = {
  modalVisible: boolean;
  onOpenChange: (open: boolean) => void;
  onReportTypeSetSuccess: () => void;
  familyInfo?: FamilyInfo;
};

const ReportSettingModal: FC<ReportSettingModalProps> = (props) => {
  const {modalVisible, onOpenChange, familyInfo, onReportTypeSetSuccess} = props;
  const [form] = Form.useForm<FamilyInfo>();

  useEffect(() => {
    if(familyInfo) {
      form.setFieldsValue(familyInfo);
    }
  }, [modalVisible]);

  const handleUpdateReportType = async (values: FamilyInfo) => {
    console.log('values', values);
    const [err, res] = await to(familyUpdate({
      id: familyInfo?.id,
      reportTypeEnum: values.reportType.toUpperCase(),
    }));
    if(err || !res) {
      message.error('更新报告生成频次失败: ' + err?.message);
      return;
    }
    onReportTypeSetSuccess();
    message.success('更新报告生成频次成功');
  }


  return (
    <ModalForm<FamilyInfo>
      title={`【${familyInfo?.name}】报告设置`}
      open={modalVisible}
      onOpenChange={(e) => {
        onOpenChange(e);
      }}
      width={600}
      form={form}
      onFinish={async (values) => {
        console.log('values', values);
        handleUpdateReportType(values)
        return true;
      }}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
      }}
    >
      <ProForm.Group style={{width: '100%'}} direction="vertical">
        <ProFormSelect
          name="reportType"
          width='xl'
          label="报告生成频次"
          options={[{
            label: '每天',
            value: 'day',
          },{
            label: '每周',
            value: 'week',
          },{
            label: '每月',
            value: 'month',
          }]}
        />
      </ProForm.Group>
    </ModalForm>
  );
};

export default ReportSettingModal;
